package ferp.center.server.servlet.game;

import ferp.center.network.request.RequestReportGet;
import ferp.center.network.response.ResponseReportGet;
import ferp.center.server.Action;
import ferp.center.server.entity.Report;
import ferp.core.Version;
import ferp.core.game.Game;
import ferp.core.player.Profile;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: olegs
 * Date: 1/26/13 6:25 PM
 */
public class GameReportGet extends HttpServlet
{
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, RequestReportGet.class, new Action.Read<RequestReportGet, ResponseReportGet>()
    {
      public ResponseReportGet run(EntityManager em, RequestReportGet input) throws IOException
      {
        Report report = em.find(Report.class, input.id);

        if (report == null)
          return null;

        ResponseReportGet result = new ResponseReportGet();

        result.snapshot = report.getSnapshot();
        result.settings = report.getSettings();
        result.statistics = report.getStatistics();
        result.version = new Version();

        String v = report.getAppVersion();
        int i = v.indexOf('(');

        result.version.name = v.substring(0, i).trim();
        result.version.code = Integer.valueOf(v.substring(i + 1, v.indexOf(')')));

        // handle old game snapshots
        if (result.version.code < 35 && !result.snapshot.startsWith("{\"actual"))
        {
          Profile.Games games = new Profile.Games();

          games.actual = Action.gson().fromJson(result.snapshot, Game.class);
          result.snapshot = Action.gson().toJson(games);
        }

        return result;
      }
    });
  }
}
